﻿class Solution {
public:
    string decodeString(string s) {
        stack<int> num;
        stack<string> str;
        str.push("");
        for (int i = 0; i < s.size();)
        {
            if (s[i] == '[')
            {
                i++;
                string tmp = "";
                while (s[i] >= 'a' && s[i] <= 'z')
                {
                    tmp += s[i++];
                }
                str.push(tmp);
            }
            else if (s[i] == ']')
            {
                int k = num.top();
                num.pop();
                string ret = str.top();
                str.pop();
                while (k--) str.top() += ret;
                i++;
            }
            else if (s[i] >= '0' && s[i] <= '9') {
                int n = 0;
                while (s[i] >= '0' && s[i] <= '9')
                {
                    n = n * 10 + (s[i] - '0');
                    i++;
                }
                num.push(n);
            }
            else {
                string tmp;
                while (i < s.size() && s[i] >= 'a' && s[i] <= 'z')
                {
                    tmp += s[i];
                    i++;
                }
                str.top() += tmp;
            }
        }
        return str.top();
    }
};